# -*- coding: utf-8 -*-
"""
This file is part of tptsig
Copyright © 2011 Telecom ParisTech, TSI
Auteur(s) : Liutkus Antoine
tptsig is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU LesserGeneral Public License
along with this program. If not, see <http://www.gnu.org/licenses/>."""

import os
import tempfile
import h5py
import random
import atexit
import string
import numpy as np

class buffer:
	"""basic buffer class, do not use hdf5, only plain numpy. data is in the data property"""
	data = None
	def __init__(self, shape):
		self.data = np.zeros(shape)

	def new(self):
		newData = buffer(self.data.shape)
		return newData
	
	def copy(self):
		newData = self.new()
		newData.data = self.data.copy()
		return newData
		
	
class hdf5Buffer(buffer):
	"""buffer class for large data, data is located in the data property, and used as a normal ndarray"""
	h5fileName = os.path.join('.','hdf5bufferTempFile.hdf5')
	h5file = None
	id = None
	data = None
	atom = None
	
	def __init__(self, atom, shape):
		self.atom = atom
		self.h5file = h5py.File(self.h5fileName, 'a')
		atexit.register(self.freeTempfile)
		self.id = ''.join(random.choice(string.letters) for i in xrange(10))
		self.data = self.h5file.create_dataset(self.id,shape,dtype=self.atom)
		
	def new(self, atom = None):
		if atom is None : atom=self.atom
		newData = hdf5Buffer(atom, self.data.shape)
		return newData
	
	def copy(self):
		newData = self.new()
		newData.data = self.data.copy()
		return newData
		
	def freeTempfile(self):
		if self.h5file is not None:
			self.h5file.close()
			self.h5file = None
		if os.path.exists(self.h5fileName):
			os.remove(self.h5fileName)
		
	def __del__(self):
		if self.h5file is not None:
			del self.h5file[self.id]
			self.h5file.close()
			

